<template lang="pug">
.upload-related
  .upload-section
    .upload-section-header
      .upload-section-title 关联材料
    .upload-section-content
      .section-info 提醒：此处与材料推荐有关，请按实际关联材料
      .section-filter
        .section-filter-input.section-filter-col
          el-cascader(:props="cascaderProps" v-model="category" size="small" clearable)
        .section-filter-input.section-filter-col
          el-select(v-model="brandId" size="small" clearable)
            el-option(v-for="item in brands" :key="item.brandId" :value="item.brandId" :label="item.name")
        .section-filter-input.section-filter-col
          el-input(placeholder="请输入搜索关键词" v-model="keyword" size="small")
        .section-filter-handle.section-filter-col
          el-button(type="primary" size="small" @click="searchMaterial") 搜索
      .material-transfer
        .left-transfer.transfer
          .transfer-header
            span 已选择 
            label {{materialSelections.length}} 
            span 条
          .transfer-list
            el-checkbox-group(v-model="materialSelections")
              el-checkbox.material-item(
                v-for="item, index in sourceData"
                :key="index"
                :label="item.id"
                :disabled="item.isDisabled"
              ) {{item.name}}
          .transfer-footer
            el-button(size="small" type="primary" @click="confirmMaterial") 确定
        .center-transfer
          .center-transfer-checkbox
            el-checkbox(v-model="form.isBothLinkMaterial" :true-label="1" :false-label="2") 单项关联
          .center-transfer-checkbox
            el-checkbox(v-model="form.isBothLinkMaterial" :true-label="2" :false-label="1") 双向关联
        .right-transfer.transfer
          .transfer-header
            span 已选择 
            label {{copyMaterialSelections.length}} 
            span 条（最多选择20条材料）
          .transfer-list
            el-checkbox-group(v-model="copyMaterialSelections")
              el-checkbox.material-item(
                v-for="item, index in targetData"
                :key="index"
                :label="item.id"
              ) {{item.name}}
          .transfer-footer
            el-button(size="small" name="primary" @click="checkAll") 全选
            el-button(size="small" type="primary" @click="deleteMaterial") 移除
  .upload-section
    .upload-section-header
      .upload-section-title 关联案例
    .upload-section-content
      .section-filter
        .section-filter-input
          el-input(placeholder="请输入搜索关键词" v-model="caseKeyword" size="small")
        .section-filter-handle
          el-button(type="primary" size="small" @click="searchCase") 搜索
      .material-transfer
        .left-transfer.transfer
          .transfer-header
            span 已选择 
            label {{caseSelections.length}} 
            span 条
          .transfer-list
            el-checkbox-group(v-model="caseSelections")
              el-checkbox.material-item(
                v-for="item, index in sourceCaseData"
                :key="index"
                :label="item.materialCaseId"
              ) {{item.projectName}}
          .transfer-footer
            el-button(size="small" name="primary" @click="checkCaseAll") 全选
            el-button(size="small" type="primary" @click="confirmCase") 确定
        .center-transfer(@click="confirmCase")
          i.iconfont.icon-next
        .right-transfer.transfer
          .transfer-header
            span 已选择 
            label {{copyCaseSelections.length}} 
            span 条
          .transfer-list
            el-checkbox-group(v-model="copyCaseSelections")
              el-checkbox.material-item(
                v-for="item, index in targetCaseData"
                :key="index"
                :label="item.materialCaseId"
              ) {{item.projectName}}
          .transfer-footer
            el-button(size="small" name="primary" @click="checkCopyCaseAll") 全选
            el-button(size="small" type="primary" @click="deleteCase") 移除
  .content-footer
    el-button(name="primary" @click="prev") 上一步，选择材料属性
    el-button(type="primary" @click="submit('save')") 提交材料信息
    el-button(name="primary" @click="submit('draft')") 存为草稿
</template>

<script>
import { getMaterialCategory, loadSupplierBrands, getApprovedMaterialList, getBaseList, saveOrUpdate } from 'api'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'related',
  data () {
    return {
      form: {
        isBothLinkMaterial: 2
      },
      cascaderProps: {
        lazy: true,
        value: 'id',
        label: 'title',
        children: 'children',
        emitPath: false,
        lazyLoad: ((node, resolve) => {
          if (!node.level) this.getMaterialCategory(node, resolve)
          else resolve()
        })
      },
      keyword: '',
      category: '',
      brandId: '',
      caseKeyword: '',
      brands: [],
      materialList: [],
      copyMaterialList: [],
      materialSelections: [],
      selectMaterialList: [],
      copyMaterialSelections: [],
      caseList: [],
      CopyCaseList: [],
      caseSelections: [],
      selectCaseList: [],
      copyCaseSelections: []
    }
  },
  computed: {
    sourceData () {
      let list = JSON.parse(JSON.stringify(this.materialList))
      return list.filter(item => this.selectMaterialList.findIndex(row => row.id === item.id) === -1)
    },
    targetData () {
      let list = JSON.parse(JSON.stringify(this.copyMaterialList))
      return list.filter(item => this.selectMaterialList.findIndex(row => row.id === item.id) > -1)
    },
    sourceCaseData () {
      let list = JSON.parse(JSON.stringify(this.caseList))
      return list.filter(item => this.selectCaseList.findIndex(row => row.materialCaseId === item.materialCaseId) === -1)
    },
    targetCaseData () {
      let list = JSON.parse(JSON.stringify(this.caseList))
      return list.filter(item => this.selectCaseList.findIndex(row => row.materialCaseId === item.materialCaseId) > -1)
    },
    ...mapState({
      materialData: state => state.material.materialData
    })
  },
  methods: {
    ...mapActions([
      'changeMaterialData'
    ]),
    async submit (val) {
      try {
        if (this.locking) return
        this.locking = true
        let queryData = { ...this.materialData.form }
        if (val === 'draft') queryData.type = 0
        else queryData.type = 1
        if (this.selectMaterialList.length) {
          queryData.isBothLinkMaterial = this.form.isBothLinkMaterial === 1 ? false : true
          queryData.linkMaterialList = this.selectMaterialList.map(item => item.id)
        }
        if (this.selectCaseList.length) {
          queryData.linkMaterialCaseList = this.selectCaseList.map(item => item.materialCaseId)
        }
        queryData.items = queryData.spec.items
        queryData.table = queryData.spec.prices
        if (val === 'draft') {
          this.$confirm('是否存为草稿？', '提示').then(async () => {
            try {
              this.submitLoading = this.$loading({
                lock: true,
                text: '数据提交中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              })
              await this.$axios.post(saveOrUpdate, { content: { ...queryData } })
              this.submitLoading.close()
              this.$message.success(this.$route.params.id ? '修改成功！' : '添加成功！')
              this.locking = false
              this.$router.back()
            } catch (err) {
              console.log(err)
              this.submitLoading.close()
              this.locking = false
              this.$message.error(err.message || err.ResultSet.errors)
            }
          })
        } else {
          this.submitLoading = this.$loading({
            lock: true,
            text: '数据提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          await this.$axios.post(saveOrUpdate, { content: { ...queryData } })
          this.submitLoading.close()
          this.$message.success(this.$route.params.id ? '修改成功！' : '添加成功！')
          this.locking = false
          this.$router.back()
        }
      } catch (err) {
        console.log(err)
        this.submitLoading.close()
        this.locking = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    prev () {
      this.$emit('prev')
    },
    checkCaseAll () {
      this.caseSelections = this.caseList.map(item => item.materialCaseId)
    },
    confirmCase () {
      this.caseSelections.map(id => {
        let item = this.caseList.find(row => row.materialCaseId === id)
        this.selectCaseList.push(item)
      })
      this.caseSelections = []
    },
    checkCopyCaseAll () {
      this.copyCaseSelections = this.selectCaseList.map(item => item.materialCaseId)
    },
    deleteCase () {
      this.copyCaseSelections.map(id => {
        let index = this.selectCaseList.findIndex(row => row.id === id)
        this.selectCaseList.splice(index, 1)
      })
      this.copyCaseSelections = []
    },
    deleteMaterial () {
      this.copyMaterialSelections.map(id => {
        let index = this.selectMaterialList.findIndex(row => row.id === id)
        this.selectMaterialList.splice(index, 1)
      })
      this.copyMaterialSelections = []
    },
    checkAll () {
      this.copyMaterialSelections = this.selectMaterialList.map(item => item.id)
    },
    confirmMaterial () {
      if (this.materialSelections.length + this.selectMaterialList.length > 20) {
        this.$message.error('关联材料最多添加20个！')
        return
      }
      this.materialSelections.map(id => {
        let item = this.materialList.find(row => row.id === id)
        this.selectMaterialList.push(item)
      })
      this.materialSelections = []
    },
    async searchMaterial () {
      try {
        let query = {}
        if (this.brandId) query.brandId = this.brandId
        if (this.category) query.categoryId = this.category
        if (this.keyword) query.keyword = this.keyword
        const { ResultSet } = await this.$axios.post(getApprovedMaterialList, { content: { ...query } })
        this.materialList = ResultSet.userData.data
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async searchCase () {
      try {
        let query = {}
        if (this.caseKeyword) query.keyword = this.caseKeyword
        const { ResultSet } = await this.$axios.post(getBaseList, { content: { ...query } })
        this.caseList = ResultSet.userData.data
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getMaterialCategory (node, resolve) {
      try {
        const { ResultSet } = await this.$axios.post(getMaterialCategory)
        resolve(ResultSet.userData.roots)
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getBrands () {
      try {
        const { ResultSet } = await this.$axios.post(loadSupplierBrands, { content: { reviewStatus: 2 } })
        this.brands = ResultSet.userData.brandList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getMaterialList () {
      try {
        const { ResultSet } = await this.$axios.post(getApprovedMaterialList)
        this.materialList = ResultSet.userData.data
        this.copyMaterialList = ResultSet.userData.data
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getCaseList () {
      try {
        const { ResultSet } = await this.$axios.post(getBaseList)
        this.caseList = ResultSet.userData.data
        this.CopyCaseList = ResultSet.userData.data
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  async created () {
    await this.getBrands()
    await this.getMaterialList()
    await this.getCaseList()
    this.form = { ...this.form, ...this.materialData.form }
    this.form.isBothLinkMaterial = this.form.isBothLinkMaterial ? 2 : 1
    if (this.form.linkMaterialList && this.form.linkMaterialList.length) {
      this.selectMaterialList = this.materialList.filter(item => this.form.linkMaterialList.findIndex(id => id === item.id) > -1)
    }
    if (this.form.linkMaterialCaseList && this.form.linkMaterialCaseList.length) {
      this.selectCaseList = this.caseList.filter(item => this.form.linkMaterialCaseList.findIndex(id => id === item.materialCaseId) > -1)
    }
  },
}
</script>

<style lang="scss" scoped>
.upload-related {
  background: #fff;
}
.upload-section {
  width: 100%;
  margin-top: 20px;
  background: #fff;
  padding: 25px 0;
  border-radius: 4px;
  display: flex;
}
.upload-section-header {
  width: 250px;
  padding: 0 22px;
  .upload-section-title {
    padding: 10px 16.5px;
    border-radius: 0 50px 50px 0;
    background: #FF708B;
    font-size: 18px;
    line-height: 26px;
    color: #fff;
  }
}
.section-info {
  font-size: 12px;
  color: #999;
  margin-bottom: 15px;
}
.section-filter {
  display: flex;
  .section-filter-col {
    flex: 1;
  }
  .section-filter-handle {
    margin-left: 40px;
  }
}
.upload-section-content {
  flex: 1;
  padding: 0 22px;
}
.material-transfer {
  display: flex;
  align-items: center;
  margin-top: 20px;
}
.transfer {
  width: 350px;
  border: 1px solid #EBEEF5;
  border-radius: 6px;
}
.transfer-header {
  background: #f5f7fa;
  height: 45px;
  line-height: 45px;
  padding: 0 15px;
  border-bottom: 1px solid #ebeef5;
  color: #363636;
  font-size: 16px;
  label {
    color: #FF2E42;
  }
}
.transfer-footer {
  background: #f5f7fa;
  height: 45px;
  line-height: 45px;
  padding: 0 15px;
}
.transfer-list {
  height: 400px;
  overflow: auto;
}
.material-item {
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  color: #606266;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
  cursor: pointer;
  .el-checkbox__label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &:last-child {
    border-bottom: none;
  }
  &:hover {
    background: #f5f5f5;
  }
}
.material-item-name {
  margin-left: 15px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.center-transfer {
  margin: 0 50px;
  .iconfont {
    font-size: 40px;
  }
}
.center-transfer-checkbox {
  margin: 15px 0;
}
.content-footer {
  margin-top: 20px;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #ebeef5;
}
</style>

<style lang="scss">
.material-item {
  .el-checkbox__label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>